import APIConfig from "../config/api";

import { wxToPromise } from "./wx";

import exceptionMessage from "../config/exception-message";

import cache from "../enum/cache"

import User from "../model/user"



class Http {

    static async request({ url, data, method = "GET" }) {
        wx.showLoading({
            title: '加载中...',
            mask: true,
        });

        let res = await wxToPromise("request", {
            url: APIConfig.baseUrl + url,
            data,
            method,
            header: {
                token: wx.getStorageSync(cache.TOKEN)
            },
            complete: () => {
                wx.hideLoading();
            }
        })

        if (res.statusCode < 400) {
            return res.data.data
        }

        //TODO 请求失败
        if (res.statusCode === 401) {
            //TODO 令牌过期相关的业务逻辑处理
            if (res.data.error_code === 10001) {
                wx.navigateTo({
                    url: "/pages/login/login"
                })
                throw new Error("请求未携带令牌")
            }


            if (refetch) {
                //token失效时，重新在进行登录
                return await Http._refetch({ url, data, method, refetch })
            }
        }

        Http._showError(res.data.error_code, res.data.message)

        const error = Http._generateMessage(res.data.message)
        throw new Error(error)


    }

    static _showError(errorCode, message) {
        let title
        title = exceptionMessage[errorCode] || message || "未知异常"
        title = Http._generateMessage(message)

        wx.showToast({
            title,
            icon: "none",
            duration: 3000
        })
    }


    static _generateMessage(message) {
        return typeof message === 'object' ? Object.values(message).join("") : message
    }


    static async _refetch(data) {
        await User.login()
        data.refetch = false
        await Http.request(data)
    }
}

export default Http